package org.nutz.jst.loader.impl;

import java.io.InputStream;
import java.net.MalformedURLException;

import javax.servlet.ServletContext;

import org.nutz.jst.impl.JstImpl;
import org.nutz.jst.loader.JstLoader;
import org.nutz.lang.Streams;

public class JstWebappLoader extends JstLoader {

    protected ServletContext sc;

    public void setServletContext(ServletContext sc) {
        this.sc = sc;
    }

    public boolean has(String key) {
        try {
            return sc.getResource(root + key) != null;
        }
        catch (MalformedURLException e) {
            return false;
        }
    }

    public JstImpl get(String key) {
        InputStream ins = sc.getResourceAsStream(root + key);
        if (ins == null)
            return null;
        byte[] buf = Streams.readBytesAndClose(ins);
        return build(buf);
    }

    public String forPrint() {
        return String.format("webapp(root=%, charset=%s)", root, charset);
    }
}
